//
//  CommodityDetailsViewController.m
//  firstpoint
//
//  Created by 泽中 on 2017/7/10.
//  Copyright © 2017年 xzcysoft. All rights reserved.
//

#import "CommodityDetailsViewController.h"
#import "PromptView.h"
#import "BuynowView.h"
#import "PSCarouselView.h"
#import "ConfirmOrderViewController.h"//确认订单
#import "SPXQButtonView.h"
#import "ShoppingCartViewController.h"//购物车
@interface CommodityDetailsViewController ()<UIWebViewDelegate,PSCarouselDelegate,UICollectionViewDelegate>
{
    BuynowView*addCardView;
    BuynowView*payView;
    NSDictionary*attDataDic;
    NSDictionary*xqDataDic;//详情
    NSArray*imgArr;//轮播图数组
    PSCarouselView*showView;
    SPXQButtonView*shoucangbuttonView;
    SPXQButtonView*gouwuchebuttonView;
    
}
@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic,strong) UIWebView *contentView;
@property ( nonatomic) UIPageControl *pageControl;
@property(nonatomic,strong)UILabel*titleLab;
@property(nonatomic,strong)UILabel*jiageLab;
@property(nonatomic,strong)UILabel*yunfeiLab;
@property(nonatomic,strong)UILabel*xiaoliangLab;
@property(nonatomic,strong)UIImageView*slIV;

@end

@implementation CommodityDetailsViewController
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden=NO;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    //       _ID=@"39";
    self.view.backgroundColor=[UIColor grayColor];
    self.title=@"商品详情";
    [self addView];
    [self setNavButton];
    [self requestAttribute];
    [self scrllerHttp];
    //    [self httpgoodDetail];
    
}
- (void)carousel:(PSCarouselView *)carousel didMoveToPage:(NSUInteger)page
{
    NSLog(@"PSCarouselView MOVE to No.%ld page",page);
    self.pageControl.currentPage = page;
}
-(void)addView{
    self.scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 64, width_screen, height_screen-50-64)];
    self.scrollView.backgroundColor = [UIColor whiteColor];
    self.scrollView.contentSize = CGSizeMake(width_screen, 500);
    [self.view addSubview:self.scrollView];
    showView = [[PSCarouselView alloc]initWithFrame:CGRectMake(0, 0, width_screen, 275)];
    showView.imageViewMode=UIViewContentModeScaleAspectFill;
    showView.pageDelegate=self;
    [self.scrollView addSubview:showView];
    
    _pageControl=[[UIPageControl alloc]initWithFrame:CGRectMake(0, 225, width_screen, 50)];
    [self.scrollView addSubview:_pageControl];
    
    //标题
    _titleLab=[[UILabel alloc]initWithFrame:CGRectMake(10, CGRectGetMaxY(showView.frame), width_screen-20, 40)];
    _titleLab.text=@"遇见过的每个人 用过来人的口吻 讲接着缘分 演绎的那么残忍 挥霍多少人 才甘心忘掉心里的人";
    _titleLab.numberOfLines=0;
    _titleLab.textColor=LRRGBColor(68, 68, 68);
    _titleLab.font=[UIFont systemFontOfSize:14];
    [self.scrollView addSubview:_titleLab];
    //价格
    _jiageLab=[[UILabel alloc]initWithFrame:CGRectMake(10, CGRectGetMaxY(self.titleLab.frame), width_screen-20, 20)];
    _jiageLab.text=@"4000元宝-2400金币";
    _jiageLab.textColor=[UIColor orangeColor];
    _jiageLab.font=[UIFont systemFontOfSize:20];
    [self.scrollView addSubview:_jiageLab];
    //运费
    _yunfeiLab=[[UILabel alloc]initWithFrame:CGRectMake(10, CGRectGetMaxY(self.jiageLab.frame)+5, width_screen/2.0-20, 15)];
    _yunfeiLab.text=@"运费：免运费";
    _yunfeiLab.textColor=[UIColor lightGrayColor];
    _yunfeiLab.font=[UIFont systemFontOfSize:12];
    [self.scrollView addSubview:_yunfeiLab];
    //销量
    _xiaoliangLab=[[UILabel alloc]initWithFrame:CGRectMake(width_screen/2.0+10, CGRectGetMaxY(self.jiageLab.frame)+5, width_screen/2.0-20, 15)];
    _xiaoliangLab.textAlignment = NSTextAlignmentRight;
    _xiaoliangLab.text=@"销量168笔";
    _xiaoliangLab.textColor=[UIColor lightGrayColor];
    _xiaoliangLab.font=[UIFont systemFontOfSize:12];
    [self.scrollView addSubview:_xiaoliangLab];
    
    //上拉图片
    self.slIV = [[UIImageView alloc]initWithFrame:CGRectMake(0,CGRectGetMaxY(self.xiaoliangLab.frame)+5, width_screen, width_screen/640.0*98)];
    self.slIV.image = [UIImage imageNamed:@"sl"];
    [self.scrollView addSubview:self.slIV];
    
    _contentView = [[UIWebView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(self.slIV.frame), width_screen , 0)];
    //    _contentView.scrollView.scrollEnabled = NO;
    _contentView.scrollView.bounces=NO;
    
    _contentView.delegate = self;
    [_contentView.scrollView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew context:nil];
    [self.scrollView addSubview:_contentView];
}

//轮播图
-(void)scrllerHttp
{
    [HTTPURL postRequest:LINK_BASE_URL(@"/goods/goodPhoto.api") parameters:@{@"goodId":@"1"} success:^(NSURLSessionDataTask *task, id responseObject) {
        NSLog(@"%@",responseObject);
        NSDictionary*dic=[PublicTools dictionaryWithJsonString:responseObject[@"data"]];
        imgArr=(NSArray*)dic;
        NSLog(@"%@",imgArr);
        NSMutableArray*arr=[NSMutableArray new];
        [imgArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            NSString*url=[NSString stringWithFormat:LINK_BASE_URL(@"%@"),obj[@"fileURL"]];
            [arr addObject:[NSURL URLWithString:url]];
        }];
        
        showView.imageURLs =arr;
        self.pageControl.numberOfPages = imgArr.count;
    } filure:^(NSURLSessionDataTask *task, id error) {
        
    }];
    
}
//加入购物车
-(void)httpAddCard
{
    NSString*tokenStr= OBJECT_FOR_KEY(@"token");
    NSString*urlStr=[NSString stringWithFormat:@"shoppingCart/save.api?access_token=%@",tokenStr];
    [HTTPURL postRequest:LINK_BASE_URL(urlStr) parameters:@{@"userId":userid,@"goodId":_ID,@"props":@"",@"buyCount":@"2",@"amount":@""} success:^(NSURLSessionDataTask *task, id responseObject) {
        NSLog(@"%@",responseObject);
        if ([responseObject[@"retFlag"]integerValue]==1) {
        [PromptView showView:responseObject[@"retInfo"] style:1];
        }
    } filure:^(NSURLSessionDataTask *task, id error) {
        [PromptView showView:@"网络请求失败"style:1];
    }];
}
//商品的详情
-(void)httpgoodDetail
{
    [HTTPURL getRequest:LINK_BASE_URL(@"goods/goodDetail.api") parameters:@{@"goodId":_ID} success:^(NSURLSessionDataTask *task, id responseObject) {
        if ([responseObject[@"retFlag"]integerValue]==1) {
        if (![responseObject[@"data"]isEqual:[NSNull null]]) {
            
            xqDataDic = [PublicTools dictionaryWithJsonString:responseObject[@"data"]];
            NSLog(@"%@",xqDataDic);
            self.xiaoliangLab.text =[NSString stringWithFormat:@"销量%@笔",xqDataDic[@"count"]];
            payView.titleLab.text=xqDataDic[@"goodName"];
            addCardView.titleLab.text=xqDataDic[@"goodName"];
            self.titleLab.text=xqDataDic[@"goodName"];
            
            payView.jiageLab.text=[NSString stringWithFormat:@"%@元宝-%@金币",xqDataDic[@"ingot"],xqDataDic[@"gold"]];
            addCardView.jiageLab.text=[NSString stringWithFormat:@"%@元宝-%@金币",xqDataDic[@"ingot"],xqDataDic[@"gold"]];
            self.jiageLab.text=[NSString stringWithFormat:@"%@元宝-%@金币",xqDataDic[@"ingot"],xqDataDic[@"gold"]];
            
            NSDictionary*dataDic = [PublicTools dictionaryWithJsonString:responseObject[@"data"]];
            NSString*htmlStr = [NSString stringWithFormat:@"<!DOCTYPE html><html><head><style type=\"text/css\">body {padding:0px;}p{margin:-3px 0;text-align:justify;}</style></head><body>%@</body></html>",dataDic[@"description"]];
            [self.contentView loadHTMLString:htmlStr baseURL:nil];
            NSLog(@"%@",dataDic);
            
        }
        }
    } filure:^(NSURLSessionDataTask *task, id error) {
        NSLog(@"%@",error);
    }];
}
//商品的属性
-(void)requestAttribute
{
    [HTTPURL postRequest:LINK_BASE_URL(@"/goods/goodAttribute.api") parameters:@{@"goodId":_ID} success:^(NSURLSessionDataTask *task, id responseObject) {
        if ([responseObject[@"retFlag"]integerValue]==1) {
        NSLog(@"%@",responseObject);
        attDataDic = [PublicTools dictionaryWithJsonString:responseObject[@"data"]];
        
        NSLog(@"%@",attDataDic);
        payView=[[BuynowView alloc]initWithFrame:CGRectMake(0, height_screen, width_screen, 340)data:attDataDic VC:self];
        
        [payView.button addTarget:self action:@selector(guanbiPayView) forControlEvents:UIControlEventTouchUpInside];
        [payView.quedingButton addTarget:self action:@selector(confirmorderButongClick) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:payView];
        
        addCardView=[[BuynowView alloc]initWithFrame:CGRectMake(0, height_screen, width_screen, 340)data:attDataDic VC:self];
        [addCardView.button addTarget:self action:@selector(guanbiPayView) forControlEvents:UIControlEventTouchUpInside];
        [addCardView.quedingButton addTarget:self action:@selector(addCardClick) forControlEvents:UIControlEventTouchUpInside];
        [addCardView.quedingButton setTitle:@"加入购物车" forState:0];
        [self.view addSubview:addCardView];
        [self httpgoodDetail];
        }
    } filure:^(NSURLSessionDataTask *task, id error) {
        
    }];
}

-(void)setNavButton
{
    UIButton*rightButton = [[UIButton alloc]initWithFrame:CGRectMake(0,0,30,25)];
    [rightButton setImage:[UIImage imageNamed:@"top"]forState:UIControlStateNormal];
    rightButton.imageView.contentMode = UIViewContentModeScaleAspectFit;
    [rightButton addTarget:self action:@selector(rightButtonClick)forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem*rightItem = [[UIBarButtonItem alloc]initWithCustomView:rightButton];
    self.navigationItem.rightBarButtonItem= rightItem;
    [self setUI];
    
    
}
-(void)rightButtonClick
{
    
}
-(void)setUI
{
    
    UIView*view=[[UIView alloc]initWithFrame:CGRectMake(0, height_screen-50, width_screen, 50)];
    view.backgroundColor=[UIColor whiteColor];
    [self.view addSubview:view];
    shoucangbuttonView=[[SPXQButtonView alloc]initWithFrame:CGRectMake(0, 0, 50, 50)];
    shoucangbuttonView.imgView.image=[UIImage imageNamed:@"grzxwdscssp"];
    shoucangbuttonView.title.text=@"收藏";
    [shoucangbuttonView.button addTarget:self action:@selector(shouchangShangPingBntCLcike) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:shoucangbuttonView];
    
    gouwuchebuttonView=[[SPXQButtonView alloc]initWithFrame:CGRectMake(50, 0, 50, 50)];
    gouwuchebuttonView.imgView.image=[UIImage imageNamed:@"grzxgwc"];
    gouwuchebuttonView.title.text=@"购物车";
    [gouwuchebuttonView.button addTarget:self action:@selector(pushShopCard) forControlEvents:64];
    [view addSubview:gouwuchebuttonView];
    //购物车按钮
    UIButton*addButton=[UIButton buttonWithType:UIButtonTypeCustom];
    addButton.frame=CGRectMake(width_screen/3, 0, width_screen/3, 50);
    addButton.backgroundColor=[UIColor orangeColor];
    [addButton setTitle:@"加入购物车" forState:0];
    [addButton addTarget:self action:@selector(addButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:addButton];
    //立即购买
    UIButton*payButton=[UIButton buttonWithType:UIButtonTypeCustom];
    payButton.frame=CGRectMake(width_screen/3*2, 0, width_screen/3, 50);
    payButton.backgroundColor=[UIColor redColor];
    [payButton setTitle:@"立即购买" forState:0];
    [payButton addTarget:self action:@selector(payButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:payButton];
    
    
}
//收藏
-(void)shouchangShangPingBntCLcike{
    [HTTPURL postRequest:LINK_BASE_URL(@"favorites/saveFavorites.api") parameters:@{@"sourceId":_ID,@"sourceType":@"2",@"userId":userid,@"name":xqDataDic[@"goodName"]} success:^(NSURLSessionDataTask *task, id responseObject) {
        NSLog(@"%@",responseObject);
        NSString *strtr = responseObject[@"retInfo"];
        if ([responseObject[@"data"]intValue]==1) {
            UIAlertView *alertview = [[UIAlertView alloc] initWithTitle:@"提示" message:strtr delegate:self cancelButtonTitle:@"确认" otherButtonTitles:nil, nil];
            [alertview show];
        }else{
            NSString *str = responseObject[@"retInfo"];
            UIAlertView *alertview = [[UIAlertView alloc] initWithTitle:@"提示" message:str delegate:self cancelButtonTitle:@"确认" otherButtonTitles:nil, nil];
            [alertview show];
        }
    } filure:^(NSURLSessionDataTask *task, id error) {
        NSLog(@"%@",error);
    }];
}
-(void)pushShopCard
{
    ShoppingCartViewController*vc=[ShoppingCartViewController new];
    
     [self.navigationController pushViewController:vc animated:YES];
    
}
-(void)addButtonClick
{
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.5];
    //设置代理
    [UIView setAnimationDelegate:self];
    //设置动画执行完毕调用的事件
    addCardView.center=CGPointMake(width_screen/2, height_screen-170);
    [UIView commitAnimations];
}
-(void)payButtonClick
{
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.5];
    //设置代理
    [UIView setAnimationDelegate:self];
    //设置动画执行完毕调用的事件
    payView.center=CGPointMake(width_screen/2, height_screen-170);
    [UIView commitAnimations];
    
}
-(void)guanbiPayView
{
    
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.5];
    //设置代理
    [UIView setAnimationDelegate:self];
    
    payView.center=CGPointMake(width_screen/2, height_screen+170);
    addCardView.center=CGPointMake(width_screen/2, height_screen+170);
    
    [UIView commitAnimations];
    
}
-(void)xuanzhong:(UIButton*)btn{
    
    NSLog(@"11111");
    btn.selected=!btn.selected;
    if (!btn.selected) {
        btn.layer.borderColor=LRRGBColor(231, 231, 231).CGColor;
        
    }else{
        btn.layer.borderColor=[UIColor orangeColor].CGColor;
    }
}
-(void)addCardQuest
{
}
//加入购物车
-(void)addCardClick
{
    [self httpAddCard];
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.5];
    //设置代理
    [UIView setAnimationDelegate:self];
    
    addCardView.center=CGPointMake(width_screen/2, height_screen+170);
    
    [UIView commitAnimations];
    
    //
}
//确认订单
-(void)confirmorderButongClick
{ConfirmOrderViewController*vc=[ConfirmOrderViewController new];
    vc.titleStr=xqDataDic[@"goodName"];
    vc.yuanbao=[NSString stringWithFormat:@"%@元宝",xqDataDic[@"ingot"]];
    vc.jinbi=[NSString stringWithFormat:@"%@金币",xqDataDic[@"gold"]];
    
    vc.shangpinId=[NSString stringWithFormat:@"%@",xqDataDic[@"id"]];
    
    [self.navigationController pushViewController:vc animated:YES];
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    
    
    return YES;
    
}
- (void)webViewDidFinishLoad:(UIWebView *)webView{
    
    NSString*jsStr=[NSString stringWithFormat:@"var aImg=document.getElementsByTagName('img');for(var i=0;i<aImg.length;i++){aImg[i].style.height=\"auto\";aImg[i].style.width=\"%fpx\";}",width_screen-30];
    [webView stringByEvaluatingJavaScriptFromString:jsStr];
    CGFloat height = [[webView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight;"] floatValue];
    
    _contentView.frame =CGRectMake(0, CGRectGetMaxY(self.slIV.frame), width_screen , height);
    self.scrollView.contentSize = CGSizeMake(width_screen, CGRectGetMaxY(self.contentView.frame));
}

//监听触发

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context

{
    if ([keyPath isEqualToString:@"contentSize"]) {
        
        //通过JS代码获取webview的内容高度
        
        CGFloat webHeight = [[_contentView stringByEvaluatingJavaScriptFromString:@"document.body.scrollHeight"] floatValue];
        
        //通过webview的contentSize获取内容高度
        
        //        self.webViewHeight = [self.showWebView.scrollView contentSize].height;
        
        CGRect newFrame = _contentView.frame;
        
        newFrame.size.height  = webHeight;
        
        _contentView.frame =newFrame;
        self.scrollView.contentSize = CGSizeMake(width_screen, CGRectGetMaxY(self.contentView.frame));
    }
}
//移除观察者
-(void)dealloc{
    [_contentView.scrollView removeObserver:self forKeyPath:@"contentSize" context:nil];
}

@end
